import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import defaultSettings from '../config/defaultSettings';
import storage from '@/utils/store';

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    return {
      settings: defaultSettings,
    };
  }
  return {
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const current = storage.getLocal('info');

      // 当 currentUser 变化时更新 initialState
      if (current) {
        setInitialState({ ...initialState, currentUser: current });
      }
      const { location } = history;

      if (current) {
        history.push(location.pathname);
        if (location.pathname === '/user/login') {
          history.push('/welcome');
          return;
        }
        if (location.pathname === '/') {
          history.push('/welcome');
          return;
        }
      }
      // 如果没有登录，重定向到 login
      if (!current && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 增加一个 loading 的状态
    childrenRender: (children: any, props: { location: { pathname: string | string[] } }) => {
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            // <SettingDrawer
            //   disableUrlParams
            //   enableDarkTheme
            //   settings={initialState?.settings}
            //   onSettingChange={(settings) => {
            //     setInitialState((preInitialState) => ({
            //       ...preInitialState,
            //       settings,
            //     }));
            //   }}
            // />
            <></>
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
